import java.util.function.IntConsumer;

/**
 * @author hewei
 * @version 1.0
 * @description: TODO
 * @date 2022/11/1 20:49
 */

public class ZeroEvenOdd3 {

    private int n;
    private volatile int cur;
    private volatile int state;

    public ZeroEvenOdd3(int n) {
        this.n = n;
        state = 0;
        cur = 1;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        while (cur <= n) {
            if (state == 0) {
                printNumber.accept(0);
                if (cur % 2 == 0) {
                    state = 2;
                } else {
                    state = 1;
                }
            }
            Thread.yield();
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while (cur <= n) {
            if (state == 2 && cur <= n) {
                printNumber.accept(cur);
                cur++;
                state = 0;
            }
            Thread.yield();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while (cur <= n) {
            if (state == 1 && cur <= n) {
                printNumber.accept(cur);
                cur++;
                state = 0;
            }
            Thread.yield();
        }
    }
}
